import React, { useState, useEffect } from "react";
import { Modal, Button } from 'antd-mobile';
const { getNewGoodsUrl } = $globalServicer("chat");
const { getGoodsPays } = $globalServicer("My");
import { showErrorToast, showSuccessToast } from '@/utils/customToast';

import styles from "./index.module.less";

/**
 * 购买套餐组件
 */
const BuyPlan = ({ visible, onClose }) => {

  const [selId, setSelId] = useState(null);
  const [planList, setPlanList] = useState([]);
  const [playLoading, setPlayLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      getPlanList();
    }
  }, [visible]);

  // 选择套餐
  const selPlan = (id) => {
    setSelId(id);
  }

  // 取消购买/关闭
  const onCancel = () => {
    setSelId(null);
    setPlanList([]);
    onClose();
  }

  // 获取套餐列表
  const getPlanList = () => {
    getNewGoodsUrl().then(res => {
      const plans = res.list || [];
      setPlanList(plans);
      if (plans.length > 0) {
        setSelId(plans[0].id); // 默认选中第一个套餐
      }
    }).catch(err => {
      console.error("获取套餐列表异常:", err);
      setPlanList([]);
    });
  }

  const openUrl = (url) => {
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    if (isMobile) {
      window.location.href = url;
    } else {
      window.open(url, "_blank", "noopener,noreferrer");
    }
  };

  const hanldePay = () => {
    if (!selId) {
      showErrorToast("请先选择要升级的套餐");
      return;
    }

    setPlayLoading(true);

    const data = {
      type: 'hupijiao_wx',
      goods_type: 4,
      goods_id: selId,
      use_balance: false,
    }

    getGoodsPays(data).then((res) => {
      if (res?.pay_info?.pay_url) {
        openUrl(res?.pay_info?.pay_url);
      } else {
        showSuccessToast("升级成功");
        onCancel();
      }
    }).catch((err) => {
      console.error("支付异常:", err);
    }).finally(() => {
      setPlayLoading(false);
    });
  }

  return (
    <Modal
      visible={visible}
      onClose={() => console.log("Modal closed")}
      className={styles.modalWrapper}
      content={
        <div className={styles.buyPlanModal}>
          <div className="top">
            <span className="material-icons icon">workspace_premium</span>
            <p className="title">今日免费次数已达上限</p>
            <p className="desc">一键解锁，无限畅玩！</p>
          </div>
          <ul className="plan-list">
            {
              planList.map((plan) => (
                <li key={plan.id} className={`plan-item ${selId === plan.id ? 'selected' : ''}`} onClick={() => selPlan(plan.id)}>
                  <div className="plan-info">
                    <p className="name">{plan.name}</p>
                    <p className="desc">{plan.description}</p>
                  </div>
                  <div className="price">
                    ¥ {plan.price}
                  </div>
                </li>
              ))
            }
          </ul>
          <div className="footer">
            <Button
              color="primary"
              onClick={hanldePay}
              disabled={!selId}
              loading={playLoading}
              loadingText="正在支付"
            >
              即刻开启畅玩
            </Button>
            <Button
              style={{ marginTop: '10px', color: '#666' }}
              fill='none'
              onClick={onCancel}
            >
              稍后查看
            </Button>
            <p className="buy-tips">如果您已经购买，请注意重复购买可能需要几分钟处理时间</p>
          </div>
        </div>
      }
    >
    </Modal>
  );
}

export default BuyPlan;